package com.study.server.message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.util.CharsetUtil;

/**
 * Created by meen on 2017/12/4.
 */
public class GameMessage extends AbstractMessage {

    public static byte HEAD[] = {0x3d, 0x4b};
    private ByteBuf content;

    public GameMessage(int cmdId) {
        super((short)cmdId);
        this.content = UnpooledByteBufAllocator.DEFAULT.directBuffer(128);
    }

    public GameMessage(short cmdId, byte[] bytes) {
        super(cmdId);
        this.content = Unpooled.wrappedBuffer(bytes);
        ;
    }

    public ByteBuf getContent() {
        return content;
    }

    public void setContent(ByteBuf content) {
        this.content = content;
    }

    @Override
    public byte getByte() {
        return this.content.readByte();
    }

    @Override
    public short getShort() {
        return this.content.readShort();
    }

    @Override
    public int getInt() {
        return this.content.readInt();
    }

    @Override
    public long getLong() {
        return this.content.readLong();
    }

    @Override
    public String getString() {
        short length = getShort();
        byte[] bs = new byte[length];
        this.content.readBytes(bs);
        return new String(bs, CharsetUtil.UTF_8);
    }

    @Override
    public void putByte(byte b) {
        this.content.writeByte(b);
    }

    @Override
    public void putShort(short s) {
        this.content.writeShort(s);
    }

    @Override
    public void putInt(int i) {
        this.content.writeInt(i);
    }

    @Override
    public void putLong(long l) {
        this.content.writeLong(l);
    }

    @Override
    public void putString(String str) {
        byte[] bytes = str.getBytes(CharsetUtil.UTF_8);
        this.content.writeShort(bytes.length);
        this.content.writeBytes(bytes);
    }

    @Override
    public int remaining() {
        return this.content.readableBytes();
    }
}
